package com.training.food.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.training.food.pojo.User;
import com.training.food.util.CommonResult;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@WebFilter(filterName = "loginFilter",urlPatterns = {"/upload/*", "/food/buy/*","/food/freeze",
        "/food/user/updatePassword", "/food/user/hasRecord", "/food/user/showExamine","/food/user/getByToken",
        "/food/user/getUserOfLogin","/food/user/hasRecord","/food/user/examineRecord","/food/user/selectRecode",
        "/food/user/updateRecode","/food/user/examine","/food/user/updateExamine","/food/user/showExamine",
        "/food/user/selectRecords","/food/user/selectUsers","/food/user/selectByUsername",
        "/food/user/selectByState","/food/user/freeLogin","/food/user/getIfRecord"
})
@Order(1)
public class LoginFilter implements Filter {

    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }
    /*
    * 过滤器拦截到响应url的请求后会先执行doFilter()方法中chain.doFilter()之前的代码，
    * 然后执行下一个过滤器或者servelt。
    * 紧接着执行chain.doFilter()之后的代码。
    *
    * */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;
        //System.out.println(request.getHeader("token"));
        //Filter过滤器跨域处理
        String origin=request.getHeader("Origin");
        response.setHeader("Access-Control-Allow-Origin",origin);
        response.setHeader("Access-Control-Allow-Methods","POST,GET,OPTIONS,PUT,DELETE");
        response.setHeader("Access-Control-Max-Age","3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin,x-requested-with,Authorization,Accept,Content-Type,token,user");
        response.setHeader("Access-Control-Allow-Credentials","true");

        //获取Headers中的参数
        String token=request.getParameter("token");
        token =token==null?"":token;
        //System.out.println("token"+token);
        //查询Redis中是否存在
        //在存储时key:value=token:user对象
        //通过查询token判断是否返回user对象
        Object user =redisTemplate.opsForValue().get(token);

        //判断redis数据库中是否存在该user对象对应的token
        if(user!=null){
            user=(User)user;
            //获取token的剩余时间
            Long expire = redisTemplate.getExpire(token);
            if(expire > 0){
                //是登录状态

                //重置token的时间
                //判断是否选择7天可登录
                if(((User) user).isNoLogin()) {

                    //如勾选了七天可登录则存储七天
                    redisTemplate.expire(token, 7L, TimeUnit.DAYS);
                }else {
                    //如未勾选七天可登录则存储一小时
                    redisTemplate.expire(token, 1L, TimeUnit.HOURS);
                }

                //放行
                //重新存储token
                servletRequest.setAttribute("user", token);
                filterChain.doFilter(servletRequest,servletResponse);
            }else{
                //未登录，响应数据
                String string = JSONObject.toJSONString(CommonResult.failed("登录失效"));

                response.setContentType("json/text;charset=utf-8");
                PrintWriter out = response.getWriter();

                out.write(string);
            }
        }

    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
